package com.hbnu.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 需求：使用PreparedStatement实现数据库的CRUD操作
 *
 * @author kittychen
 * @since 2025-10-21 10:19
 */
public class JdbcDemo05 {

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/class2309?serverTimezone=GMT&useSSL=false";
            String username = "root";
            String password = "123456";
            connection = DriverManager.getConnection(url, username, password);

            // 自己独立完成修改、删除、查询等操作
            String sql = "insert into tb_user(id, username, password, salary) values(?, ?, ?, ?)";
            preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setInt(1, 4);
            preparedStatement.setString(2, "lisi");
            preparedStatement.setString(3, "123456");
            preparedStatement.setDouble(4, 10000);
            int rows = preparedStatement.executeUpdate();

            System.out.println(rows == 1 ? "添加成功" : "添加失败");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
